﻿using Dapper_Core.BLL.Interface;
using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Dapper_Core.BLL.Impl
{
    public class PersonalAccount_ResetPwdBusiness : BaseRepository<PersonalAccount_ResetPwd>, IPersonalAccount_ResetPwdBusiness
    {
        private string WorkflowCode = "F03_PersonalAccount_ResetPwd";

        public PersonalAccount_ResetPwdBusiness()
        {

        }

        public PersonalAccount_ResetPwdBusiness(TransactionContext transactionContext) : base(transactionContext)
        {

        }

        public (bool success, string message) Submit(PersonalAccount_ResetPwd resetPwd, string currentCheckMan, string action, string taskId = null)
        {
            try
            {
                bool success = false;
                string message = "";
                WorkflowInstance workflowInstance = new WorkflowInstance();
                WorkflowRecord workflowRecord = new WorkflowRecord();
                List<WorkflowTask> nextWorkflowTaskList = new List<WorkflowTask>();
                V_WorkflowTransition nextWorkflowTransition = new V_WorkflowTransition();
                if (string.IsNullOrEmpty(taskId))
                {
                    (success, message) = WorkflowCommonBusiness.HandleSubmit(resetPwd.Id, resetPwd.DeptId, "feiYanfa", WorkflowCode, currentCheckMan, "密码丢失重置提交", out workflowInstance, out workflowRecord, out nextWorkflowTaskList);
                    if (!success) return (success, message);
                    using(TransactionContext tranContext = new TransactionContext())
                    {
                        try
                        {
                            tranContext.BeginTransaction();
                            new BaseRepository<PersonalAccount_ResetPwd>(tranContext).Add(resetPwd);
                            new BaseRepository<WorkflowInstance>(tranContext).Add(workflowInstance);
                            new BaseRepository<WorkflowTask>(tranContext).AddList(nextWorkflowTaskList);
                            new BaseRepository<WorkflowRecord>(tranContext).Add(workflowRecord);
                            tranContext.Commit();
                        }
                        catch (Exception ex)
                        {
                            NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "密码丢失重置提交失败（内层）", $"resetPwd={JsonConvert.SerializeObject(resetPwd)}，currentCheckMan={currentCheckMan}，action={action}，taskId={taskId}", ex, "DapperCore");
                            tranContext.Rollback();
                            return (false, AlertMessage.SubmitException);
                        }
                    }
                }
                else
                {
                    string remarks = (!string.IsNullOrEmpty(action) && action.EndsWith("_Pass")) ? "密码丢失重置重新提交" : "密码丢失重置撤销";
                    (success, message) = WorkflowCommonBusiness.HandleAudit(taskId, resetPwd.DeptId, "feiYanfa", currentCheckMan, action, remarks, out workflowInstance, out workflowRecord, out nextWorkflowTaskList, out nextWorkflowTransition);
                    if (!success) return (success, message);
                    using (TransactionContext tranContext = new TransactionContext())
                    {
                        try
                        {
                            tranContext.BeginTransaction();
                            #region 更新PersonalAccount_ResetPwd
                            resetPwd.ModifyDate = workflowRecord.CreateDate;
                            resetPwd.Modifier = currentCheckMan;
                            new BaseRepository<PersonalAccount_ResetPwd>(tranContext).Update(resetPwd);
                            #endregion

                            #region 更新WorkflowInstance
                            new BaseRepository<WorkflowInstance>(tranContext).Update(workflowInstance);
                            #endregion

                            #region 插入WorkflowRecord
                            new BaseRepository<WorkflowRecord>(tranContext).Add(workflowRecord);
                            #endregion

                            #region 更新当前任务的状态 && 插入下一步的任务
                            BaseRepository<WorkflowTask> workflowTaskRepository = new BaseRepository<WorkflowTask>(tranContext);
                            WorkflowTask workflowTask = workflowTaskRepository.Get(taskId);
                            workflowTask.State = "inactive";
                            workflowTaskRepository.Update(workflowTask);
                            workflowTaskRepository.AddList(nextWorkflowTaskList);
                            #endregion

                            if (nextWorkflowTransition.ToCode.EndsWith("_Finished"))//审批通过流程结束
                            {
                                resetPwd.Remarks = resetPwd.Remarks + ";审批通过流程结束";
                                new BaseRepository<PersonalAccount_ResetPwd>(tranContext).Update(resetPwd);
                            }
                            else if((nextWorkflowTransition.ToCode.EndsWith("_Closed")))//撤销审批
                            {
                                resetPwd.Remarks = resetPwd.Remarks + ";撤销审批";
                                new BaseRepository<PersonalAccount_ResetPwd>(tranContext).Update(resetPwd);
                            }
                            
                            tranContext.Commit();
                        }
                        catch (Exception ex)
                        {
                            NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "密码丢失重置提交失败（内层）", $"resetPwd={JsonConvert.SerializeObject(resetPwd)}，currentCheckMan={currentCheckMan}，action={action}，taskId={taskId}", ex, "DapperCore");
                            tranContext.Rollback();
                            return (false, AlertMessage.SubmitException);
                        }
                    }
                }
                return (success, message);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "密码丢失重置提交失败（外层）", $"resetPwd={JsonConvert.SerializeObject(resetPwd)}，currentCheckMan={currentCheckMan}，action={action}，taskId={taskId}", ex, "DapperCore");
                return (false, AlertMessage.SubmitException);
            }
        }

        public (bool success, string message) Audit(string taskId, string currentCheckMan, string action, string remarks)
        {
            try
            {
                bool success = false;
                string message = "";
                WorkflowInstance workflowInstance = new WorkflowInstance();
                WorkflowRecord workflowRecord = new WorkflowRecord();
                List<WorkflowTask> nextWorkflowTaskList = new List<WorkflowTask>();
                V_WorkflowTransition nextWorkflowTransition = new V_WorkflowTransition();

                #region 获取WorkflowTask
                Expression<Func<V_WorkflowTask, bool>> workflowTaskExp = a => a.TaskId == taskId;
                List<V_WorkflowTask> vworkflowTaskList = new BaseRepository<V_WorkflowTask>().GetList(workflowTaskExp).ToList();
                if (vworkflowTaskList == null || vworkflowTaskList.Count < 1)
                {
                    return (false, "未获取到相关任务信息，请联系管理员");
                }
                V_WorkflowTask vworkflowTask = vworkflowTaskList[0];
                #endregion

                #region 获取PersonalAccount_ResetPwd
                PersonalAccount_ResetPwd resetPwd = new BaseRepository<PersonalAccount_ResetPwd>().Get(vworkflowTask.WorkflowTypeId);
                if (resetPwd == null)
                {
                    return (false, "未获取到相关申请信息，请联系管理员");
                }
                #endregion

                (success, message) = WorkflowCommonBusiness.HandleAudit(taskId, resetPwd.DeptId, "feiYanfa", currentCheckMan, action, remarks, out workflowInstance, out workflowRecord, out nextWorkflowTaskList, out nextWorkflowTransition);
                if (!success) return (success, message);
                using (TransactionContext tranContext = new TransactionContext())
                {
                    try
                    {
                        tranContext.BeginTransaction();

                        #region 更新WorkflowInstance
                        new BaseRepository<WorkflowInstance>(tranContext).Update(workflowInstance);
                        #endregion

                        #region 插入WorkflowRecord
                        new BaseRepository<WorkflowRecord>(tranContext).Add(workflowRecord);
                        #endregion

                        #region 更新当前任务的状态 && 插入下一步的任务
                        BaseRepository<WorkflowTask> workflowTaskRepository = new BaseRepository<WorkflowTask>(tranContext);
                        WorkflowTask workflowTask = workflowTaskRepository.Get(taskId);
                        workflowTask.State = "inactive";
                        workflowTaskRepository.Update(workflowTask);
                        workflowTaskRepository.AddList(nextWorkflowTaskList);
                        #endregion

                        if (nextWorkflowTransition.ToCode.EndsWith("_Finished"))//审批通过流程结束
                        {
                            resetPwd.Remarks = resetPwd.Remarks + ";审批通过流程结束";
                            new BaseRepository<PersonalAccount_ResetPwd>(tranContext).Update(resetPwd);
                        }
                        else if ((nextWorkflowTransition.ToCode.EndsWith("_Closed")))//撤销审批
                        {
                            resetPwd.Remarks = resetPwd.Remarks + ";撤销审批";
                            new BaseRepository<PersonalAccount_ResetPwd>(tranContext).Update(resetPwd);
                        }

                        tranContext.Commit();
                    }
                    catch (Exception ex)
                    {
                        NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "密码丢失重置审批失败（内层）", $"taskId={taskId}，currentCheckMan={currentCheckMan}，action={action}，remarks={remarks}", ex, "DapperCore");
                        tranContext.Rollback();
                        return (false, AlertMessage.SubmitException);
                    }
                }
                return (success, message);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "密码丢失重置审批失败（外层）", $"taskId={taskId}，currentCheckMan={currentCheckMan}，action={action}，remarks={remarks}", ex, "DapperCore");
                return (false, AlertMessage.AuditException);
            }
        }
    }
}
